package com.xiejr.actuator.socket.scanners;

import com.xiejr.actuator.annotations.TopicHandler;
import com.xiejr.actuator.socket.config.TopicSocketFactoryBean;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.context.annotation.ClassPathBeanDefinitionScanner;
import org.springframework.core.type.filter.TypeFilter;

import java.util.Set;

/**
 * @program: socket-actuator-spring-boot-starter
 * @description: socket扫描器
 * @author: xjr
 * @create: 2020-07-13 14:55
 **/
public class SocketClasspathScanner extends ClassPathBeanDefinitionScanner {
    public SocketClasspathScanner(BeanDefinitionRegistry registry) {
        super(registry,false);
    }

    /**
     *
     * @description 注册过滤逻辑
     * @author xiejiarong
     * @date 2020年07月13日 14:56
     */
    public void registerFilter(TypeFilter typeFilter){
        this.addIncludeFilter(typeFilter);
    }

    /**
     *
     * @description 得到扫描结果
     * @param basePackages:  包
     * @return
     * @author xiejiarong
     * @date 2020年07月13日 15:01
     */
    @Override
    protected Set<BeanDefinitionHolder> doScan(String... basePackages) {
        Set<BeanDefinitionHolder> beanDefinitionHolders=super.doScan(basePackages);
        beanDefinitionHolders.forEach(data->{
            GenericBeanDefinition definition= (GenericBeanDefinition) data.getBeanDefinition();
            String beanClassName=definition.getBeanClassName();
            TopicHandler topic= null;
            Class topicClass= null ;
            try {
                topicClass = Class.forName(beanClassName);
                topic = (TopicHandler) topicClass.getAnnotation(TopicHandler.class);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
            definition.getConstructorArgumentValues().addGenericArgumentValue(beanClassName);
            definition.getConstructorArgumentValues().addGenericArgumentValue(topic.value());
            definition.setAutowireMode(2);
            definition.setLazyInit(false);
            definition.setBeanClass(TopicSocketFactoryBean.class);
            this.getRegistry().registerBeanDefinition(topic.value(),definition);
        });
        return beanDefinitionHolders;
    }
}
